﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Yuchen.Log.Utils;
using Yuchen.SOA.Utils;
namespace Xinchen.SOA.GateWay
{
    public class DispatcherHandler : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var uri = new Uri(string.Format("http://{0}/{1}/{2}{3}", ApplicationContext.Current.ServiceHostingAddress,
                ApplicationContext.Current.ServiceName.Split('.').LastOrDefault(), ApplicationContext.Current.Action, request.RequestUri.Query));
            var writer = LogWriter.GetInstance();
            writer.WriteLogFile(GetType().Name, "开始转发请求：" + uri.ToString());
            return await Task.Factory.StartNew(() =>
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("ApplicationId", ApplicationContext.Current.ApplicationId);
                client.DefaultRequestHeaders.Add("ApplicationKey", request.Headers.GetValue("ApplicationKey"));
                client.DefaultRequestHeaders.Add("FromGateway", "1");
                using (client)
                {
                    return client.PostAsync(uri, request.Content).Result;
                }
            });
        }
    }
}
